package com.bosssoft.boss_exam_web.Controller;


import com.bosssoft.boss_exam_core.enums.business.ExamPaperCheckEnum;
import com.bosssoft.boss_exam_core.exception.UpdateEntityException;
import com.bosssoft.boss_exam_core.util.web.ResponseUtil;
import com.bosssoft.boss_exam_db.entity.ApplicantQuestionScore;
import com.bosssoft.boss_exam_db.service.busines.AdminService;
import com.bosssoft.boss_exam_db.service.busines.ApplicantExamPaperService;
import com.bosssoft.boss_exam_db.service.busines.ApplicantQuestionScoreService;
import com.bosssoft.boss_exam_web.common.annotation.LoginAdmin;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.TransactionDefinition;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.support.DefaultTransactionDefinition;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/admin/applicantQuestionScore")
@Validated
@Slf4j
@Api(value="应聘者考试得分控制器")
public class ApplicantQuestionScoreController {

    // 引入阅卷记录服务
    @Autowired
    private ApplicantQuestionScoreService applicantQuestionScoreService;

    // 引入管理员服务
    @Autowired
    private AdminService adminService;

    //  引入应聘人考试试卷服务
    @Autowired
    private ApplicantExamPaperService applicantExamPaperService;

    //引入事务管理器
    @Autowired
    @Qualifier("transactionManager")
    private PlatformTransactionManager transactionManager;

    @ApiOperation(value = "未阅读的卷子题目查询", notes = "可根据考试、试卷、应聘者ID、查询未批阅的答题记录", httpMethod = "GET", response = Object.class)
    @ApiImplicitParams({
            @ApiImplicitParam(name = "examId", value = "考试ID", dataType = "String", required = true, dataTypeClass = String.class),
            @ApiImplicitParam(name = "examPaperId", value = "试卷ID", dataType = "String", required = true, dataTypeClass = String.class),
            @ApiImplicitParam(name = "applicantId", value = "应聘者ID", dataType = "String", required = true, dataTypeClass = String.class),
    })
    @GetMapping("/noCheckAnswers")
    public Object quesyNoCheckAnswers(@LoginAdmin String adminId,
                       @RequestParam String examId,
                       @RequestParam String examPaperId,
                       @RequestParam String applicantId) {
        if (adminId == null) {
            return ResponseUtil.unlogin();
        }
        List<ApplicantQuestionScore> applicantQuestionScores = applicantQuestionScoreService.queryNoCheckExamPaper(examId, examPaperId, applicantId, ExamPaperCheckEnum.NO_CHECK.getCode());
        return ResponseUtil.ok(applicantQuestionScores);
    }

    @ApiOperation(value = "阅卷官阅卷", notes = "阅卷官对某个应聘者的答卷进行批阅", httpMethod = "POST", response = Object.class)
    @ApiImplicitParams({
            @ApiImplicitParam(name = "applicantQuestionScores", value = "阅卷官阅卷记录集合", dataType = "List<ApplicantQuestionScore>", required = true, dataTypeClass = List.class),
    })
    @PostMapping("/bashInsert")
    public Object insetBashRecord(@LoginAdmin String  adminId, @RequestBody List<ApplicantQuestionScore> applicantQuestionScores) {

//       引入编程事务
        DefaultTransactionDefinition defaultTransactionDefinition = new DefaultTransactionDefinition();
//       设置事务传播行为：required 如有事务加入事务，无事务新建一起事务
//       作用将多个service操作都使用同一个connection事务
        defaultTransactionDefinition.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRED);
        TransactionStatus status = transactionManager.getTransaction(defaultTransactionDefinition);
        try {
            if (adminId == null) {
                return ResponseUtil.unlogin();
            }
            List<ApplicantQuestionScore> applicantQuestionScoreList = applicantQuestionScores.stream().map(item -> {
                item.setAdminId(adminId);
                return item;
            }).collect(Collectors.toList());
            // 应聘人题目答题记录都修改 （修改内容为阅卷官阅卷信息）
            Integer recordNum = applicantQuestionScoreService.updateCheckRecod(applicantQuestionScoreList);
            // 试卷设置为修改
            // fixme 事务
            if (applicantQuestionScoreList != null && applicantQuestionScoreList.size() != 0) {
                ApplicantQuestionScore applicantQuestionScore = applicantQuestionScoreList.get(0);
                // 试卷ID
                String examPaperId = applicantQuestionScore.getExamPaperId();
                // 考试ID
                String examId = applicantQuestionScore.getExamId();
                // 应聘人ID
                String applicantId = applicantQuestionScore.getApplicantId();
                // 修改试卷状态
                Integer result = this.applicantExamPaperService.noTxUpdataChecked(examId, examPaperId, applicantId);
            }
            // 事务提交
            transactionManager.commit(status);
            return ResponseUtil.ok();
        }catch (Exception e){
            transactionManager.rollback(status);
            throw new UpdateEntityException(e);
        }
    }
}
